import store from '@/store/modules/user';
export const socketConnect = {
  socket: null,
  onMessageCallBack: null,
  isReconnecting: false,
  connect: function () {
    this.socket = new WebSocket('ws://localhost:8889/websocket/' + store.state.userInfo.id);
    // this.socket = new WebSocket('ws://192.168.31.198:8889/websocket/' + store.state.userInfo.id);
    this.socket.onopen = function () {
      console.log('WebSocket 连接成功');
    };

    this.socket.onmessage = (e) => {
      const message = e.data;
      if (this.onMessageCallBack) {
        this.onMessageCallBack(JSON.parse(message));
      }
    };

    this.socket.onerror = (err) => {
      console.log('WebSocket 错误:', err);
    };

    this.socket.onclose = (msg) => {
      console.log(msg, '连接关闭');
    };
  },

  reconnect: function () {
    if (!this.isReconnecting) {
      this.isReconnecting = true;
      setTimeout(() => {
        this.connect();
        this.isReconnecting = false;
      }, 2000); // 2秒后尝试重新连接
    }
  },

  onSend: function (msg) {
    if (this.socket?.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(msg));
    } else {
      console.log('WebSocket没有连接, 正在重新连接...');
      this.reconnect(); // 2秒后尝试重新连接
    }
  },

  onMessage: function (callback) {
    this.onMessageCallBack = callback;
  },

  onClose: function () {
    this.socket.close();
  },
};
